package com.tailyou.androidlearning202400

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.tailyou.androidlearning202400.util.ToastUtil

class Activity1 : AppCompatActivity() {

    private lateinit var btnStart: Button
    private lateinit var edtParams1: EditText

    // 因为Activity1启动Activity2，需要Activity2回传参数，所以，需要使用ActivityResultLauncher来启动
    private var launcher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                ToastUtil.showToast(this, result.data?.extras?.getString("params2"))
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_1)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        btnStart = findViewById(R.id.btnStart)
        edtParams1 = findViewById(R.id.edtParams1)
        btnStart.setOnClickListener {
            // Activity1启动Activity2，并传递参数
            val intent = Intent(this, Activity2::class.java)
            intent.putExtra("params1", edtParams1.text.toString())
            launcher.launch(intent)
        }
    }
}